import React, { useEffect } from 'react'
import { useSelector, useDispatch, shallowEqual } from 'react-redux'
import * as actions from 'store/action'
import Button from 'components/Button'

import './style.less'

function List({ history }) {
  const { list } = useSelector((state) => ({ list: state.list }), shallowEqual)
  const dispatch = useDispatch()

  const onDelete = (item) => {
    dispatch(actions.delUsers(item.id))
  }

  useEffect(() => {
    dispatch(actions.getList())
  }, [dispatch])

  return (
    <div className="container">
      <div className="title">用户管理</div>
      <div style={{ margin: '18px 0' }}>
        <Button type="primary" onClick={() => history.push('/detail/create')}>
          新建用户
        </Button>
      </div>
      <table className="table" cellSpacing="0" cellPadding="0">
        <thead>
          <tr>
            <th>姓名</th>
            <th>用户名</th>
            <th>邮箱</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {list.map((item) => (
            <tr key={item.id}>
              <td>{item.name}</td>
              <td>{item.user}</td>
              <td>{item.email}</td>
              <td>
                <Button text onClick={() => history.push(`/detail/edit/${item.id}`)}>
                  编辑
                </Button>
                <Button text onClick={() => onDelete(item)}>
                  删除
                </Button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

export default List
